package ru.ifmo.croak.impl.stress.post.team1.fromTextFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.PostService;
import ru.ifmo.croak.util.CroakFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.UUID;

public class PostStressMain implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(PostStressMain.class);
    private static final int AUTHORS_NUMBER = 100;
    private static final int AUTHOR_LEN = 10;
    private static final String filename = "WarAndPeace.txt";
    private static final double SPACES_PERCENT = 0.05;
    private final Random random = new Random(1);
    private final PostService postService;
    private ArrayList<String> authors;

    public PostStressMain(String name) {
        String postProviderName = CroakFactory.getInstance().getProperty(name + ".provider");
        postService = CroakFactory.getInstance().getImplementation(PostService.class, postProviderName);
    }

    private String randomString(int maxLen) {
        int len = random.nextInt(maxLen) + 1;
        char[] s = new char[len];
        for (int i = 0; i < len; i++) {
            if (random.nextDouble() < SPACES_PERCENT) {
                s[i] = ' ';
            } else {
                s[i] = (char) ('a' + random.nextInt('z' - 'a'));
            }
        }
        return new String(s);
    }


    public void run() {
        authors = new ArrayList<String>();
        for (int i = 0; i < AUTHORS_NUMBER; i++) {
            authors.add(randomString(AUTHOR_LEN));
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF8"));
            StringBuilder sb = new StringBuilder();
            while (true) {
                String s = br.readLine();
                if (s == null) break;
                sb.append(s).append(" ");
            }
            StringTokenizer st = new StringTokenizer(sb.toString(), ".!?");
            int i = 0;
            while (st.hasMoreTokens()) {
                postService.postMessage(makeMessage(getAuthor(), st.nextToken(), i++ * 1000 ));
            }
            br.close();
            log.info("Posting done");
        } catch (IOException e) {
            log.error("IOException", e);
        }
    }

    private Message makeMessage(String author, String s, int time) {
        Message message = new Message();
        message.setId(UUID.randomUUID());
        message.setTime(time);
        message.setAuthor(author);
        message.setText(s);
        return message;
    }

    private String getAuthor() {
        return authors.get(random.nextInt(authors.size()));
    }
}
